class TaskManager {
    constructor() {
        this.apiBaseUrl = '/api/tasks';
        this.init();
    }

    async init() {
        await this.bindEvents();
        await this.loadTasks();
    }

    async bindEvents() {
        document.getElementById('taskForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.addTask();
        });
    }

    async apiCall(endpoint, options = {}) {
        try {
            const response = await fetch(`${this.apiBaseUrl}${endpoint}`, {
                headers: {
                    'Content-Type': 'application/json',
                    ...options.headers
                },
                ...options
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            this.showError(`网络请求失败: ${error.message}`);
            throw error;
        }
    }

    async loadTasks() {
        this.showLoading(true);
        try {
            const tasks = await this.apiCall('/');
            this.renderTasks(tasks);
            this.updateStats(tasks);
        } catch (error) {
            console.error('加载任务失败:', error);
        } finally {
            this.showLoading(false);
        }
    }

    async addTask() {
        const taskInput = document.getElementById('taskInput');
        const title = taskInput.value.trim();

        if (!title) return;

        this.setSubmitState(true);

        try {
            await this.apiCall('/', {
                method: 'POST',
                body: JSON.stringify({ title })
            });
            
            taskInput.value = '';
            await this.loadTasks();
        } catch (error) {
            console.error('添加任务失败:', error);
        } finally {
            this.setSubmitState(false);
        }
    }

    async toggleTask(id, completed) {
        try {
            await this.apiCall(`/${id}`, {
                method: 'PUT',
                body: JSON.stringify({ completed: !completed })
            });
            await this.loadTasks();
        } catch (error) {
            console.error('更新任务失败:', error);
        }
    }

    async deleteTask(id) {
        if (!confirm('确定要删除这个任务吗？')) return;

        try {
            await this.apiCall(`/${id}`, {
                method: 'DELETE'
            });
            await this.loadTasks();
        } catch (error) {
            console.error('删除任务失败:', error);
        }
    }

    renderTasks(tasks) {
        const taskList = document.getElementById('taskList');
        const emptyMessage = document.getElementById('emptyMessage');

        if (tasks.length === 0) {
            taskList.innerHTML = '';
            emptyMessage.classList.remove('d-none');
            return;
        }

        emptyMessage.classList.add('d-none');
        
        taskList.innerHTML = tasks.map(task => `
            <div class="list-group-item task-item ${task.completed ? 'task-completed' : ''}">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="form-check flex-grow-1">
                        <input class="form-check-input" type="checkbox" 
                               ${task.completed ? 'checked' : ''} 
                               onchange="taskManager.toggleTask(${task.id}, ${task.completed})"
                               style="transform: scale(1.2);">
                        <label class="form-check-label task-title ms-3 fs-6">
                            ${this.escapeHtml(task.title)}
                        </label>
                        <div class="text-muted small mt-1 ms-3">
                            <i class="bi bi-clock"></i> ${new Date(task.createdAt).toLocaleString()}
                        </div>
                    </div>
                    <div class="btn-action">
                        <button class="btn btn-outline-danger btn-sm" 
                                onclick="taskManager.deleteTask(${task.id})">
                            删除
                        </button>
                    </div>
                </div>
            </div>
        `).join('');
    }

    updateStats(tasks) {
        const total = tasks.length;
        const completed = tasks.filter(task => task.completed).length;
        const pending = total - completed;

        document.getElementById('stats').textContent = 
            `总计: ${total} | 待完成: ${pending} | 已完成: ${completed}`;
    }

    showLoading(show) {
        const loading = document.getElementById('loadingMessage');
        const taskList = document.getElementById('taskList');
        
        if (show) {
            loading.classList.remove('d-none');
            taskList.classList.add('d-none');
        } else {
            loading.classList.add('d-none');
            taskList.classList.remove('d-none');
        }
    }

    setSubmitState(loading) {
        const submitText = document.getElementById('submitText');
        const submitSpinner = document.getElementById('submitSpinner');
        const submitButton = document.querySelector('#taskForm button[type="submit"]');

        if (loading) {
            submitText.textContent = '添加中...';
            submitSpinner.classList.remove('d-none');
            submitButton.disabled = true;
        } else {
            submitText.textContent = '添加任务';
            submitSpinner.classList.add('d-none');
            submitButton.disabled = false;
        }
    }

    showError(message) {
        const errorElement = document.getElementById('errorMessage');
        errorElement.textContent = message;
        errorElement.classList.remove('d-none');
        
        setTimeout(() => {
            errorElement.classList.add('d-none');
        }, 5000);
    }

    escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
}

// 初始化应用
const taskManager = new TaskManager();